package com.ehome.poct.base.device.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ehome.context.context.SpringContextHolder;
import com.ehome.core.service.AbstractCrudServiceImpl;
import com.ehome.exception.BizException;
import com.ehome.poct.base.api.constant.BizCode;
import com.ehome.poct.base.api.dto.device.DeviceVersionReqDTO;
import com.ehome.poct.base.api.dto.device.SoftwareUpgradeQry;
import com.ehome.poct.base.api.dto.device.TestDeviceVersionDTO;
import com.ehome.poct.base.api.dto.device.VersionStatusQry;
import com.ehome.poct.base.api.virtual.TestDeviceVersionService;
import com.ehome.poct.base.mqtt.MqttGateway;
import com.ehome.poct.base.device.repository.TestDeviceVersionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 版本表SerivceImlp
 *
 * @author yjm
 * @Date 2021-12-06 16:53
 */
@Service
public class TestDeviceVersionSerivceImlp extends AbstractCrudServiceImpl<TestDeviceVersionDTO> implements TestDeviceVersionService {
    @Autowired
    private TestDeviceVersionRepository testDeviceVersionRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MqttGateway mqttGateway;
    private static final String PALMPOCT_TODO = "ehome_public_msg";

    @Override
    public void sendmqtt(DeviceVersionReqDTO reqDto) {
        // 1. 从缓存中查询
//        final var obj = redisTemplate.opsForValue().get(PALMPOCT_TODO + reqDto.getData().getVersion());
        reqDto.setPublishTime(LocalDateTime.now().toString());
//        if (ObjectUtil.isEmpty(obj)) {
        mqttGateway.sendToMqtt(JSON.toJSONString(reqDto), PALMPOCT_TODO);
//            redisTemplate.opsForValue().set(PALMPOCT_TODO + reqDto.getData().getVersion(), JSON.toJSONString(reqDto), 1, TimeUnit.DAYS);
//        }
    }

    @Override
    public void editStatus(VersionStatusQry qry) {
        testDeviceVersionRepository.updateStatus(qry);
    }

    @Override
    protected void preInsert(TestDeviceVersionDTO dto, Map<String, Object> map) {
        String activeProfiles = SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[1];
        boolean any = StrUtil.containsAny(activeProfiles, "develop", "beta");
        String version = dto.getVersion();
        boolean match = ReUtil.isMatch("\\d+(\\.\\d+){2}", version);
        if(!match && !any){
            throw new BizException(BizCode.VERSION_FORMAT_ERROR);
        }
        if(any){
            version = StrUtil.subBefore(dto.getVersion(),"_",false);
        }
        if (dto.getPackageType() != 2){
            if (ObjectUtil.isEmpty(dto.getPackageId()) || ObjectUtil.isEmpty(dto.getPackageName())){
                throw new BizException(BizCode.PACKAGEID);
            }
        }
        if (dto.getPackageType().equals(0) || dto.getPackageType().equals(1)) {
            if (testDeviceVersionRepository.selVersion(dto.getVersion(), dto.getPackageId(), dto.getDeviceType(), dto.getPackageType())) {
                throw new BizException(BizCode.VERSION_ERROR);
            }
            if (testDeviceVersionRepository.getSoftVersionCode(dto.getPackageType(), dto.getDeviceType(),dto.getPackageId() , dto.getVersionCode())) {
                throw new BizException(BizCode.VERSION_CODE_ERROR);
            }
        } else {
            if (testDeviceVersionRepository.selectVersion(dto.getVersion(), dto.getDeviceType(), dto.getPackageType())) {
                throw new BizException(BizCode.VERSION_ERROR);
            }
            if (testDeviceVersionRepository.getVersionCode(dto.getPackageType(), dto.getDeviceType(), dto.getVersionCode())) {
                throw new BizException(BizCode.VERSION_CODE_ERROR);
            }
        }

        super.preInsert(dto, map);
    }

    @Override
    protected void preUpdate(TestDeviceVersionDTO dto, Map<String, Object> map) {
        String activeProfiles = SpringContextHolder.getApplicationContext().getEnvironment().getActiveProfiles()[1];
        boolean any = StrUtil.containsAny(activeProfiles, "develop", "beta");
        String version = dto.getVersion();
        boolean match = ReUtil.isMatch("\\d+(\\.\\d+){2}", version);
        if(!match && !any){
            throw new BizException(BizCode.VERSION_FORMAT_ERROR);
        }
        if(any){
            version = StrUtil.subBefore(version,"_",false);
        }
        super.postUpdate(dto, map);
    }

    @Override
    public List<TestDeviceVersionDTO> getNewVersion(TestDeviceVersionDTO dto) {
        return testDeviceVersionRepository.newVersion(dto);
    }

    @Override
    public List<TestDeviceVersionDTO> getSoftwareUpgradeInfo(SoftwareUpgradeQry qry) {
        return testDeviceVersionRepository.getSoftwareUpgradeInfo(qry);
    }
}